package org.numanint.wizard;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
import org.numanint.Activator;
import org.numanint.code.AddJspGenerator;
import org.numanint.code.BaseDaoGenerator;
import org.numanint.code.BoGenerator;
import org.numanint.code.BoXmlGenerator;
import org.numanint.code.ControllerGenerator;
import org.numanint.code.ControllerXmlGenerator;
import org.numanint.code.ConventUtils;
import org.numanint.code.DaoGenerator;
import org.numanint.code.DaoXmlGenerator;
import org.numanint.code.EditJspGenerator;
import org.numanint.code.GeneratorProperties;
import org.numanint.code.HbmGenerator;
import org.numanint.code.HibernateCfgGenerator;
import org.numanint.code.IndexJspGenerator;
import org.numanint.code.ListJspGenerator;
import org.numanint.code.PojoGenerator;
import org.numanint.code.ReverseEngineer;
import org.numanint.code.ShowJspGenerator;
import org.numanint.utils.UIutils;
import org.osgi.framework.Bundle;


public class WebProjectWizardOne extends Wizard implements INewWizard {
	private WizardNewProjectCreationPage creationPage;

	private ProgressMonitorDialog dialog;
	public static IProject project; 
	// 给向导加上向导页
	

	public void addPages() {
		creationPage = new WizardNewProjectCreationPage("");
		creationPage.setTitle("Numanint-新建一个Web框架");
		creationPage.setDescription("创建一个Web框架,基于spring 2.5.x和hibernate3.x");
		creationPage.setImageDescriptor(UIutils.getImageDescriptor("/icons/numanint-48.png"));
		
		addPage(creationPage);
		addPage(new WebProjectWizardTwo());
		addPage(new WebProjectWizardThree());
	}

	public void saveWebProjectConfig() {
		WebProjectConfig.projectWorkspacePath = creationPage.getLocationPath() + System.getProperty("file.separator") + creationPage.getProjectName()
		+ System.getProperty("file.separator");
		//WebProjectConfig.workspacePath = creationPage.getLocationPath() + System.getProperty("file.separator");
		WebProjectConfig.projectName = creationPage.getProjectName();	
		project = creationPage.getProjectHandle();	
	}

	private void unzipBlankFramework() throws Exception {
		Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
		InputStream is = FileLocator.toFileURL(bundle.getEntry("resources/"+WebProjectConfig.blankFrameworkName+".zip")).openStream();
		UIutils.unjar(is, WebProjectConfig.projectWorkspacePath);

	}

	private void importBlankFramework() throws Exception {	
		
		//project=ResourcesPlugin.getWorkspace().getRoot().getProject(WebProjectConfig.projectName);
		IPath projectPath = new Path(WebProjectConfig.projectWorkspacePath + ".project");
		final IProjectDescription description = ResourcesPlugin.getWorkspace().loadProjectDescription(projectPath);
		NullProgressMonitor monitor = new NullProgressMonitor();
		project.create(description, monitor);
		project.open(IResource.BACKGROUND_REFRESH, new SubProgressMonitor(monitor, 1000));	

	}

	private void updateBlankFramwork() throws Exception{
		UIutils.txtFileReplace(WebProjectConfig.projectWorkspacePath + ".project", WebProjectConfig.blankFrameworkName, WebProjectConfig.projectName);
		UIutils.txtFileReplace(WebProjectConfig.projectWorkspacePath + ".settings"+System.getProperty("file.separator")+"org.eclipse.wst.common.component", WebProjectConfig.blankFrameworkName, WebProjectConfig.projectName);
		UIutils.txtFileReplace(WebProjectConfig.projectWorkspacePath + System.getProperty("file.separator")+
				"WebContent" + System.getProperty("file.separator")+
				"WEB-INF"+ System.getProperty("file.separator")+
				"web.xml"
				, WebProjectConfig.blankFrameworkName, WebProjectConfig.projectName);
		UIutils.txtFileReplace(WebProjectConfig.projectWorkspacePath + System.getProperty("file.separator")+
				"WebContent" + System.getProperty("file.separator")+
				"WEB-INF"+ System.getProperty("file.separator")+
				"applicationContext.xml"
				, "<!--<property name=\"configLocation\" value=\"classpath:org/xwlabs/pojo/hibernate.cfg.xml\"/>-->", "<property name=\"configLocation\"  value=\"classpath:"+WebProjectConfig.pojoPkgName.replace('.','/')+"/hibernate.cfg.xml\"/>");		
		UIutils.txtFileReplace(WebProjectConfig.projectWorkspacePath + System.getProperty("file.separator")+
				"WebContent" + System.getProperty("file.separator")+
				"WEB-INF"+ System.getProperty("file.separator")+
				"properties"+System.getProperty("file.separator")+
				"log4j.properties"
				, WebProjectConfig.blankFrameworkName, WebProjectConfig.projectName);
		UIutils.txtFileReplace(WebProjectConfig.projectWorkspacePath + System.getProperty("file.separator")+
				"WebContent" + System.getProperty("file.separator")+
				"WEB-INF"+ System.getProperty("file.separator")+
				"properties"+System.getProperty("file.separator")+
				"jdbc.properties"
				, "jdbc.driverClassName=", "jdbc.driverClassName="+WebProjectConfig.projectDBConfig.driver+System.getProperty("line.separator")+"#");
		UIutils.txtFileReplace(WebProjectConfig.projectWorkspacePath + System.getProperty("file.separator")+
				"WebContent" + System.getProperty("file.separator")+
				"WEB-INF"+ System.getProperty("file.separator")+
				"properties"+System.getProperty("file.separator")+
				"jdbc.properties"
				, "jdbc.url=", "jdbc.url="+WebProjectConfig.projectDBConfig.url+System.getProperty("line.separator")+"#");
		UIutils.txtFileReplace(WebProjectConfig.projectWorkspacePath + System.getProperty("file.separator")+
				"WebContent" + System.getProperty("file.separator")+
				"WEB-INF"+ System.getProperty("file.separator")+
				"properties"+System.getProperty("file.separator")+
				"jdbc.properties"
				, "jdbc.username=", "jdbc.username="+WebProjectConfig.projectDBConfig.username+System.getProperty("line.separator")+"#");
		UIutils.txtFileReplace(WebProjectConfig.projectWorkspacePath + System.getProperty("file.separator")+
				"WebContent" + System.getProperty("file.separator")+
				"WEB-INF"+ System.getProperty("file.separator")+
				"properties"+System.getProperty("file.separator")+
				"jdbc.properties"
				, "jdbc.password=", "jdbc.password="+WebProjectConfig.projectDBConfig.password+System.getProperty("line.separator")+"#");

	}
	
	private void generatorBlankFramwork() throws Exception{
		
		GeneratorProperties properties = new GeneratorProperties();
		properties.setProjectName(WebProjectConfig.projectName);
		properties.setProjectDir(WebProjectConfig.projectWorkspacePath);
		properties.setSampleName("sample");
		properties.setPojoPkgName(WebProjectConfig.pojoPkgName);
		properties.setDaoPkgName(WebProjectConfig.daoPkgName);
		properties.setBoPkgName(WebProjectConfig.boPkgName);
		properties.setControllerPkgName(WebProjectConfig.controllerPkgName);
		
		
		ReverseEngineer reveng = new ReverseEngineer(WebProjectConfig.conn,WebProjectConfig.projectModelTableNames,WebProjectConfig.selectedSchema);
		reveng.reverse(	);
		
		PojoGenerator pojoGenerator = new PojoGenerator(properties);
		pojoGenerator.setOutputDir(properties.getProjectDir()+"src/");
		pojoGenerator.setTemplateFilename("pojo.ftl");
		pojoGenerator.generator(reveng);
		
		HbmGenerator hbmGenerator = new HbmGenerator(properties);
		hbmGenerator.setOutputDir(properties.getProjectDir()+"src/");
		hbmGenerator.setTemplateFilename("hbm.ftl");
		hbmGenerator.generator(reveng);
		
		DaoGenerator daoGenerator = new DaoGenerator(properties);
		daoGenerator.setOutputDir(properties.getProjectDir()+"src/");
		daoGenerator.setTemplateFilename("dao.ftl");
		daoGenerator.generator(reveng);
		
		BaseDaoGenerator baseDaoGenerator = new BaseDaoGenerator(properties);
		baseDaoGenerator.setOutputDir(properties.getProjectDir()+"src/");
		baseDaoGenerator.setTemplateFilename("baseDao.ftl");
		baseDaoGenerator.generator(reveng);
		
		HibernateCfgGenerator hibernateCfgGenerator = new HibernateCfgGenerator(properties);
		hibernateCfgGenerator.setOutputDir(properties.getProjectDir()+"src/");
		hibernateCfgGenerator.setTemplateFilename("hibernate.cfg.ftl");
		hibernateCfgGenerator.generator(reveng);	

		BoGenerator boGenerator = new BoGenerator(properties);			
		boGenerator.setProperties(properties);
		boGenerator.setOutputDir(properties.getProjectDir()+"src/");
		boGenerator.setTemplateFilename("bo.ftl");
		boGenerator.generator(reveng);
		
		ControllerGenerator controllerGenerator = new ControllerGenerator(properties);
		controllerGenerator.setOutputDir(properties.getProjectDir()+"src/");
		controllerGenerator.setTemplateFilename("controller.ftl");
		controllerGenerator.generator(reveng);

		DaoXmlGenerator daoXmlGenerator = new DaoXmlGenerator(properties);
		daoXmlGenerator.setOutputDir(properties.getProjectDir()+"WebContent/WEB-INF/daoXml/");
		daoXmlGenerator.setTemplateFilename("dao.xml.ftl");
		daoXmlGenerator.generator(reveng);

		BoXmlGenerator boXmlGenerator = new BoXmlGenerator(properties);
		boXmlGenerator.setOutputDir(properties.getProjectDir()+"WebContent/WEB-INF/boXml/");
		boXmlGenerator.setTemplateFilename("bo.xml.ftl");
		boXmlGenerator.generator(reveng);
		
		ControllerXmlGenerator controllerXmlGenerator = new ControllerXmlGenerator(properties);
		controllerXmlGenerator.setOutputDir(properties.getProjectDir()+"WebContent/WEB-INF/controllerXml/");			
		controllerXmlGenerator.setTemplateFilename("controller.xml.ftl");
		controllerXmlGenerator.generator(reveng);	
		
		ListJspGenerator listJspGenerator = new ListJspGenerator(properties);
		listJspGenerator.setOutputDir(properties.getProjectDir()+"WebContent/"+ConventUtils.lowerFirstChar(properties.getProjectName())+"/"+properties.getSampleName()+"/");
		listJspGenerator.setTemplateFilename("jsp/list.jsp.ftl");
		listJspGenerator.generator(reveng);	
		
		AddJspGenerator addJspGenerator = new AddJspGenerator(properties);
		addJspGenerator.setOutputDir(properties.getProjectDir()+"WebContent/"+ConventUtils.lowerFirstChar(properties.getProjectName())+"/"+properties.getSampleName()+"/");
		addJspGenerator.setTemplateFilename("jsp/add.jsp.ftl");
		addJspGenerator.generator(reveng);	
		
		EditJspGenerator editJspGenerator = new EditJspGenerator(properties);
		editJspGenerator.setOutputDir(properties.getProjectDir()+"WebContent/"+ConventUtils.lowerFirstChar(properties.getProjectName())+"/"+properties.getSampleName()+"/");
		editJspGenerator.setTemplateFilename("jsp/edit.jsp.ftl");
		editJspGenerator.generator(reveng);	
		
		ShowJspGenerator showJspGenerator = new ShowJspGenerator(properties);
		showJspGenerator.setOutputDir(properties.getProjectDir()+"WebContent/"+ConventUtils.lowerFirstChar(properties.getProjectName())+"/"+properties.getSampleName()+"/");
		showJspGenerator.setTemplateFilename("jsp/show.jsp.ftl");
		showJspGenerator.generator(reveng);	
		
		IndexJspGenerator indexJspGenerator = new IndexJspGenerator(properties);
		indexJspGenerator.setOutputDir(properties.getProjectDir()+"WebContent/"+ConventUtils.lowerFirstChar(properties.getProjectName())+"/"+properties.getSampleName()+"/");
		indexJspGenerator.setTemplateFilename("jsp/index.jsp.ftl");
		indexJspGenerator.generator(reveng);
	}
	
	// 在向导上点完成时，调用向导页的finish()方法。
	@Override
	public boolean performFinish() {

		saveWebProjectConfig();// 保存工程参数

		IRunnableWithProgress runnable = new IRunnableWithProgress (){
			public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
				try{		
					monitor.beginTask("Start...",1000);
					monitor.worked(10);
					Thread.sleep(50);
					unzipBlankFramework();// 解压空工程
					monitor.setTaskName("解压空工程...");
					monitor.worked(30);
					Thread.sleep(500);
					updateBlankFramwork();//更新空工程
					monitor.setTaskName("更新空工程...");
					monitor.worked(40);
					Thread.sleep(500);
					importBlankFramework();// 导入空工程ba
					monitor.setTaskName("导入空工程...");
					monitor.worked(50);
					Thread.sleep(500);
					generatorBlankFramwork();//生成工程基础pojo，dao，xml
					monitor.setTaskName("生成工程基础pojo,dao,bo,controller,xml...");
					monitor.worked(90);
					Thread.sleep(500);
					project.refreshLocal(IResource.DEPTH_INFINITE, null);
					monitor.setTaskName("刷新建立的工程...");
					monitor.worked(100);
					Thread.sleep(500);
					monitor.done();
				}catch(Exception e){
					//MessageDialog.openError(getShell(),"错误信息",e.getMessage()); 
					e.printStackTrace();
				}
			}
		};
		
		dialog = new ProgressMonitorDialog(getShell());
			try {
			dialog.run(true,true,runnable);
			} catch (InvocationTargetException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
			} catch (InterruptedException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
			}
		return true;
	}


	// 向导初始化的时候，设置向导的标题，新建向导页

	public void init(IWorkbench workbench, IStructuredSelection selection) {
		setNeedsProgressMonitor(true);
		setWindowTitle("Numanint-新建一个Web框架");
	}
	
	
}
